using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Configuration;
using System.Collections;

namespace CISExchangeDaemonService
{
    public partial class CISExchangeDaemon : ServiceBase
    {
        public static Hashtable Settings;

        public CISExchangeDaemon()
        {
            InitializeComponent();
            
        }

        public static DateTime startTime = DateTime.Now;

        protected override void OnStart(string[] args)
        {
            String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = System.IO.Path.GetDirectoryName(path);
            Directory.SetCurrentDirectory(path);
            Settings = new Hashtable();
            LoadSettings();
            string ip = CISExchangeDaemon.Settings["IPaddress"] as string;
            int port = int.Parse(CISExchangeDaemon.Settings["Port"] as string);
            
            Server.StartServerThread(ip, port);
        }

        protected override void OnStop()
        {
            Server.StopServer();
        }

        protected override void OnCustomCommand(Int32 Command)
        {
            if (Command == 128)
            {
                Server.StartUserManagerThread();
            }
        }

        private static void LoadSettings()
        {
            String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = System.IO.Path.GetDirectoryName(path);
            Directory.SetCurrentDirectory(path);
            string filename = Directory.GetCurrentDirectory() + "\\CIS Exchange Daemon.config";

            try
            {
                FileStream fs;
                fs = File.Open(filename, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    try
                    {
                        string[] temp = line.Split('=');
                        Settings.Add(temp[0], temp[1]);
                    }
                    catch
                    {
                        EventLog.WriteEntry("Exchange Daemon Service", "Blad przy wczytywaniu pliku konfiguracyjnego");
                        sr.Close();
                        fs.Close();
                    }
                }
                sr.Close();
                fs.Close();
            }
            catch
            {
                EventLog.WriteEntry("Exchange Daemon Service", "Blad przy wczytywaniu pliku konfiguracyjnego");
            }
        }
    }
}
